package com.emailsystem.emailsystem.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.emailsystem.emailsystem.common.ApiRestResponse;
import com.emailsystem.emailsystem.domain.Connection;
import com.emailsystem.emailsystem.domain.Email;
import com.emailsystem.emailsystem.domain.User;
import com.emailsystem.emailsystem.exception.MailExceptionEnum;
import com.emailsystem.emailsystem.service.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

@RestController
@RequestMapping("/email")
public class EmailController {
    @Autowired
    private ClientService clientService;
    @Autowired
    private UserService userService;
//    @Autowired
//    private EmailService emailService;

    @Autowired
    private SmtpService smtpService;
    @Autowired
    private ServerService serverService;
    private String receiveProtocol;

    Email email=new Email();

    @PostMapping("/getDeleted")
    public ApiRestResponse getDeleted(@RequestBody JSONObject object) {
        String account = (String) object.get("account");
        ArrayList<Email> deleted = clientService.getDeleted(account);
        JSONArray deletedObjects = JSONArray.parseArray(JSON.toJSONString(deleted));
        return ApiRestResponse.success(deletedObjects);
    }

    @PostMapping("/updateEmailState")
    public void updateEmailState(@RequestBody JSONObject Object) {
         email.setEmailID(Object.get("emailID").toString());
         String type=Object.get("type").toString();
         boolean state= (boolean) Object.get("state");
        clientService.updateEmail(email.getEmailID(),type,state);
    }
    @PostMapping("/receivedByPOP3")
    public ApiRestResponse getReceivedEmailByPOP3(@RequestBody User user) throws IOException {
        //用账号获取
        String account= user.getAccount();
        //这个是数据库内某个行为的Email数量
        Integer numsInDB = clientService.getEmailNumsInPOP3(account, 'r');
        System.out.printf("现存数量================================="+numsInDB+"封");
        //然后和qq现存数量比较
        String password = userService.getPassword(account);
        //数量的差值
        int delta=clientService.DBvsCurrent(numsInDB,account,password);
        //有新邮件 就加到数据库
        if(delta>0){
            //现在这个函数只插入email
           clientService.receiveEmails("POP3","",account, password,numsInDB+1,delta);
        }
        //有没有插入都从DB获取
        ArrayList<Email> emails = clientService.getAllEmails(account,"inbox");
        //无更新邮件 返回空值
        JSONArray receivedObjects = JSONArray.parseArray(JSON.toJSONString(emails));
        return ApiRestResponse.success(receivedObjects);
    }

    @PostMapping("/receivedByIMAP")
    public ApiRestResponse getReceivedEmailByIMAP(@RequestBody JSONObject object) throws IOException {
        //用账号获取
        String boxType= object.get("boxType").toString();

        String account=object.get("account").toString();
        Integer numsInDB = clientService.getEmailNumsInIMAP(account, boxType);
        System.out.printf("现存数量================================="+numsInDB+"封");
        String password = userService.getPassword(account);
        int delta=clientService.DBvsCurrentInIMAP(numsInDB,boxType,account, password);
        //远程邮箱 这个boxtype不存在
        if(delta==-1){
            return ApiRestResponse.error(MailExceptionEnum.WRONG_BOX_TYPE);
        }
        if (delta > 0) {
            clientService.receiveEmails("IMAP",boxType,account, password,numsInDB+1,delta);
        }
        ArrayList<Email> emails = clientService.getAllEmails(account,boxType);
        JSONArray receivedObjects = JSONArray.parseArray(JSON.toJSONString(emails));
        return ApiRestResponse.success(receivedObjects);
    }
    @GetMapping("/downloadAttachment")
    public ApiRestResponse downloadAttachment(@RequestParam String account,String filename, HttpServletResponse response) {
        try {
//            User user=new User();
//            user.setAccount(object.get("account").toString());
//            String filename=object.get("filename").toString();
            //路径上中文不是中文 得先解码
            filename=URLDecoder.decode(filename, "UTF-8");
            //String account = user.getAccount();
            account=account.substring(0,account.lastIndexOf('@'));
            System.out.printf(account);
            // path是指想要下载的文件的路径
            File file = new File("./receiveAttachment/"+account+"/"+filename);
            // 获取文件名
//            File file = new File("D:/软件开发实训/ESMaster/email-system/"+filename);
            String fileName = file.getName();
            // 获取文件后缀名
            String ext = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();

            // 将文件写入输入流
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();

            // 清空response
            response.reset();
            // 设置response的Header
            response.setCharacterEncoding("UTF-8");
            //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
            //attachment表示以附件方式下载   inline表示在线打开   "Content-Disposition: inline; filename=文件名.mp3"
            // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            // 告知浏览器文件的大小
            response.addHeader("Content-Length", "" + file.length());
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
//            response.setContentType("application/octet-stream");
            outputStream.write(buffer);
            outputStream.flush();
//            System.out.println("222");
//            return ApiRestResponse.success(buffer);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return  ApiRestResponse.success();
    }

    @PostMapping("/setReceiveProtocol")
    public ApiRestResponse setReceiveProtocol(@RequestBody JSONObject object) throws IOException {
      this.receiveProtocol=object.get("Protocol").toString();
      return  ApiRestResponse.success();
    }

    @GetMapping("/getReceiveProtocol")
    public ApiRestResponse getReceiveProtocol() throws IOException {
        JSONObject object=new JSONObject();
        if(this.receiveProtocol!=null) {
            object.put("Protocol", this.receiveProtocol);
            return ApiRestResponse.success(object);
        }else{
            return ApiRestResponse.success();
        }
    }

    SimpleDateFormat sdf=new SimpleDateFormat("/yyyy/MM/dd");
    @PostMapping("/sendEmail")
    @ResponseBody
    public ApiRestResponse sendEmail(@RequestBody JSONObject data) throws Exception {
        if (!StringUtils.hasLength(data.get("sender").toString())) {
            return ApiRestResponse.error(MailExceptionEnum.NEED_SENDER);
        }
        if (!StringUtils.hasLength(data.get("receiver").toString())) {
            return ApiRestResponse.error(MailExceptionEnum.NEED_RECEIVER);
        }
        if (!StringUtils.hasLength(data.get("content").toString())) {
            return ApiRestResponse.error(MailExceptionEnum.NEED_CONTEXT);
        }
        email.setSender(data.get("sender").toString());
        email.setReceiver(data.get("receiver").toString());
        email.setContent(data.get("content").toString());
        email.setSubject(data.get("subject").toString());
        //相对
        File fileFold=new File("src\\main\\resources\\file\\"+userService.getCurrentUser().getAccount());
       /// String[] filegroup=new String[fileFold.listFiles().length];
        ArrayList<File> filegroup=new ArrayList<>();
        if(fileFold.isDirectory()){
            File[] files=fileFold.listFiles();
            for(int i=0;i<files.length;i++){
               // filegroup[i]=files[i].getPath();
                //System.out.println(filegroup[i]);
               filegroup.add(files[i]);
            }
        }
      //  email.setAttachmentPath(filegroup);
        email.setAttachment(filegroup);
        String password = userService.getPassword((String) data.get("sender"));

        if (data.get("sender").toString().contains("163.com")) {
            smtpService.SMTPService(email,"smtp.163.com", data.get("password").toString());
        } else if (data.get("sender").toString().contains("qq.com")) {
            smtpService.SMTPService(email,"smtp.qq.com", password);
        } else {
            Connection connection = new Connection();
            if (!StringUtils.hasLength(data.get("port").toString())) {
                return ApiRestResponse.error(MailExceptionEnum.NEED_PORT);
            }
            if (!StringUtils.hasLength(data.get("ip").toString())) {
                return ApiRestResponse.error(MailExceptionEnum.NEED_IP);
            }
//            connection.setPort((Integer) data.get("port"));
//            connection.setServerIP(data.get("ip").toString());
//            JSONObject object = emailService.sendEmail(email);
//            if (!serverService.getServerStatus()) {
//                return ApiRestResponse.error(MailExceptionEnum.SERVER_IS_NOT_START);
//            }
//            clientService.connect(connection, object);
        }
        JSONObject res=new JSONObject();
        res.put("sender",email.getSender());
        res.put("receive",email.getReceiver());
        res.put("content",email.getContent());
        return ApiRestResponse.success();
    }

    @PostMapping("/upload")
    @ResponseBody
    public ApiRestResponse upload(@RequestPart("file") MultipartFile file, HttpServletRequest req) throws IOException, InterruptedException {
        String originName=file.getOriginalFilename();
        String url="";
//        if(originName.endsWith(".pdf")){
//            return ApiRestResponse.error(MailExceptionEnum.File_IO_EXCEPTION);
//        }
        String format= sdf.format(new Date());
//        String realPath=req.getServletContext().getRealPath("/")+format;
        //相对
        String realPath="src\\main\\resources\\file\\"+userService.getCurrentUser().getAccount();
        File folder= new File(realPath);
        System.out.println(realPath);
        if(!folder.exists()) {
            folder.mkdirs();
        }
        //生产任意字符串+名字作为新名字
        //  String newName= UUID.randomUUID().toString()+originName;
        String newName=originName;
        int count=0;
        if(folder.isDirectory()){
            File[] files=folder.listFiles();
            for(int i=0;i<files.length;i++){
                if(files[i].getName().startsWith(originName)){
                    count++;
                    newName=originName+"("+count+")";
                }
            }
        }
        try{
            file.transferTo(new File(folder,newName));
            url=req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+format+newName;
            ApiRestResponse.success();
        }catch (IOException e){
            ApiRestResponse.error(MailExceptionEnum.INSERT_FAILED);
        }
        JSONObject res=new JSONObject();
        res.put("url", url);
        return ApiRestResponse.success(res);
    }

    @GetMapping("/getFileList")
    public ApiRestResponse getFileList() throws IOException {
        //修改成相对路径
        String realPath="src\\main\\resources\\file\\"+userService.getCurrentUser().getAccount();
//        FileWriter fileWriter = new FileWriter(realPath);
        File folder= new File(realPath);
        if(!folder.exists()){
            folder.mkdirs();
        }
        String[]filegroup=new String[folder.listFiles().length];
        long[]fileSize=new long[folder.listFiles().length];
        String[]lastModify=new String[folder.listFiles().length];
        JSONObject res=new JSONObject();
        if(folder.isDirectory()){
            File[] files=folder.listFiles();
            for(int i=0;i<files.length;i++){
                filegroup[i]=files[i].getName();
                fileSize[i]=files[i].length();
                lastModify[i]=new Timestamp(files[i].lastModified()).toString();
                System.out.println(filegroup[i]);
            }
            res.put("fileList",filegroup);
            res.put("fileSize",fileSize);
            res.put("lastModify",lastModify);
            return ApiRestResponse.success(res);
        }else{
            return ApiRestResponse.error(MailExceptionEnum.READ_FOLDER_ERROR);
        }
    }

    @PostMapping("/deleteFile")
    public  ApiRestResponse deleteFile(@RequestBody JSONObject data){
        boolean flag=false;
        System.out.println("filename"+data.get("filename").toString());

        //相对
        String realPath="src\\main\\resources\\file\\"+userService.getCurrentUser().getAccount()+"/"+data.get("filename").toString();
        System.out.println(realPath);
        File file = new File(realPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        if(flag==true)
            return  ApiRestResponse.success();
        else
            return  ApiRestResponse.error(MailExceptionEnum.FILE_FALL_TO_DELETE);
    }
    //旧
//    @GetMapping("/receiveEmail")
//    public void receive() {
//        emailService.receiveEmail();
//    }
//旧
//
//    /**
//     * 查看历史邮件
//     */
//    @PostMapping("/all")
//    public ApiRestResponse getAllEmail(@RequestBody User user){
//        //用账号获取完成行为
//        String account= user.getAccount();
//        Completion completion=userService.getCompletionByAccount(account);
//        //没有完成的行为或者没有收发的邮件
//        if(null == completion||(completion.getSentEmail().length()==0&&completion.getReceiveEmail().length()==0)){
//            return ApiRestResponse.error(MailExceptionEnum.CHECK_HISTORY_ERR);
//        }
//        //整理获取收发的邮件
//        String sentEmail= completion.getSentEmail();
//        String receiveEmail = completion.getReceiveEmail();
//        ArrayList<String> allEmail = new ArrayList<>();
//        if (sentEmail != null) {
//            allEmail.addAll(List.of(sentEmail.split(",")));
//        }
//        if (receiveEmail != null) {
//            allEmail.addAll(List.of(receiveEmail.split(",")));
//        }
//        JSONArray AllObjects=new JSONArray();
//        for(String tmp:allEmail){
//            JSONObject obj = new JSONObject();
//            Email email=emailService.getEmailByEmailID(tmp);
////            obj.put("emailID",email.getEmailID());
//            obj.put("sender",email.getSender());
//            obj.put("receiver",email.getReceiver());
//            obj.put("attachment",email.getAttachment());
//            obj.put("content",email.getContent());
//            obj.put("subject",email.getSubject());
//            obj.put("sendTime",email.getSendTime());
//            AllObjects.add(obj);
//        }
//
//        return ApiRestResponse.success(AllObjects);
//    }
//
//    //下面几个函数都是仿照上面的函数就行了
//    /**
//     * 查看收藏邮件
//     */
//    @PostMapping("/collect")
//    public ApiRestResponse getFavouriteEmail(@RequestBody User user){
//        //用账号获取完成行为
//        String account= user.getAccount();
//        Completion completion=userService.getCompletionByAccount(account);
//        //没有收藏的邮件
//        if(null == completion||(completion.getFavouriteEmail().length()==0)){
//            return ApiRestResponse.error(MailExceptionEnum.CHECK_FAVOURITE_ERR);
//        }
//        //整理获取收藏的邮件
//        String favouriteEmail= completion.getFavouriteEmail();
//        ArrayList<String> favouriteEmails = new ArrayList<>();
//        favouriteEmails.addAll(List.of(favouriteEmail.split(",")));
//        JSONArray favouriteObjects=new JSONArray();
//        for(String tmp:favouriteEmails){
//            JSONObject obj = new JSONObject();
//            Email email=emailService.getEmailByEmailID(tmp);
//            //obj.put("emailID",email.getEmailID());
//            obj.put("sender",email.getSender());
//            obj.put("receiver",email.getReceiver());
//            obj.put("attachment",email.getAttachment());
//            obj.put("content",email.getContent());
//            obj.put("subject",email.getSubject());
//            obj.put("sendTime",email.getSendTime());
//            favouriteObjects.add(obj);
//        }
//        return ApiRestResponse.success(favouriteObjects);
//    }
//
//    /**
//     * 查看草稿箱
//     */
//    @PostMapping("/draft")
//    public ApiRestResponse getDraftEmail(@RequestBody User user){
//        //用账号获取完成行为
//        String account= user.getAccount();
//        Completion completion=userService.getCompletionByAccount(account);
//        //没有草稿的邮件
//        if(null == completion||(completion.getDraftEmail().length()==0)){
//            return ApiRestResponse.error(MailExceptionEnum.CHECK_DRAFT_ERR);
//        }
//        //整理获取草稿的邮件
//        String draftEmail= completion.getDraftEmail();
//        ArrayList<String> draftEmails = new ArrayList<>();
//        draftEmails.addAll(List.of(draftEmail.split(",")));
//        JSONArray draftObjects=new JSONArray();
//        for(String tmp:draftEmails){
//            JSONObject obj = new JSONObject();
//            Email email=emailService.getEmailByEmailID(tmp);
//            //obj.put("emailID",email.getEmailID());
//            obj.put("sender",email.getSender());
//            obj.put("receiver",email.getReceiver());
//            obj.put("attachment",email.getAttachment());
//            obj.put("content",email.getContent());
//            obj.put("subject",email.getSubject());
//            obj.put("sendTime",email.getSendTime());
//            draftObjects.add(obj);
//        }
//        return ApiRestResponse.success(draftObjects);
//    }
//    /**
//     * 仅查看已接受
//     */
//    @PostMapping("/received")
//    public ApiRestResponse getReceicedEmail(@RequestBody User user){
//        //用账号获取完成行为
//        String account= user.getAccount();
//        Completion completion=userService.getCompletionByAccount(account);
//        //没有已接收的邮件
//        if(null == completion||(completion.getReceiveEmail().length()==0)){
//            return ApiRestResponse.error(MailExceptionEnum.CHECK_RECEIVE_ERR);
//        }
//        //整理获取收到的邮件
//        String receivedEmail= completion.getReceiveEmail();
//        ArrayList<String> receivedEmails = new ArrayList<>();
//        receivedEmails.addAll(List.of(receivedEmail.split(",")));
//        JSONArray receivedObjects=new JSONArray();
//        for(String tmp:receivedEmails){
//            JSONObject obj = new JSONObject();
//            Email email=emailService.getEmailByEmailID(tmp);
//            //obj.put("emailID",email.getEmailID());
//            obj.put("sender",email.getSender());
//            obj.put("receiver",email.getReceiver());
//            obj.put("attachment",email.getAttachment());
//            obj.put("content",email.getContent());
//            obj.put("subject",email.getSubject());
//            obj.put("sendTime",email.getSendTime());
//            receivedObjects.add(obj);
//        }
//        return ApiRestResponse.success(receivedObjects);
//    }
//    /**
//     * 仅查看已发送
//     */
//    @PostMapping("/sent")
//    public ApiRestResponse getSentEmail(@RequestBody User user){
//        //用账号获取完成行为
//        String account= user.getAccount();
//        Completion completion=userService.getCompletionByAccount(account);
//        //没有发送过邮件
//        if(null == completion||(null==completion.getSentEmail())){
//            return ApiRestResponse.error(MailExceptionEnum.CHECK_SENT_ERR);
//        }
//        //整理获取发送过的邮件
//        String sentEmail= completion.getSentEmail();
//        ArrayList<String> sentEmails = new ArrayList<>();
//        sentEmails.addAll(List.of(sentEmail.split(",")));
//        JSONArray sentObjects=new JSONArray();
//        for(String tmp:sentEmails){
//            JSONObject obj = new JSONObject();
//            Email email=emailService.getEmailByEmailID(tmp);
//            //obj.put("emailID",email.getEmailID());
//            obj.put("sender",email.getSender());
//            obj.put("receiver",email.getReceiver());
//            obj.put("attachment",email.getAttachment());
//            obj.put("content",email.getContent());
//            obj.put("subject",email.getSubject());
//            obj.put("sendTime",email.getSendTime());
//            sentObjects.add(obj);
//        }
//        return ApiRestResponse.success(sentObjects);
//    }
//    /**
//     * 查看垃圾邮件
//     */
//    @PostMapping("/rubbish")
//    public ApiRestResponse getRubbishEmail(@RequestBody User user){
//        //用账号获取完成行为
//        String account= user.getAccount();
//        Completion completion=userService.getCompletionByAccount(account);
//        //没有收到垃圾邮件
//        if(null == completion||(null==completion.getRubbishEmail())){
//            return ApiRestResponse.error(MailExceptionEnum.CHECK_RUBBISH_ERR);
//        }
//        //整理获取垃圾邮件
//        String rubbishEmail= completion.getRubbishEmail();
//        ArrayList<String> rubbishEmails = new ArrayList<>();
//        rubbishEmails.addAll(List.of(rubbishEmail.split(",")));
//        JSONArray rubbishObjects=new JSONArray();
//        for(String tmp:rubbishEmails){
//            JSONObject obj = new JSONObject();
//            Email email=emailService.getEmailByEmailID(tmp);
//            //obj.put("emailID",email.getEmailID());
//            obj.put("sender",email.getSender());
//            obj.put("receiver",email.getReceiver());
//            obj.put("attachment",email.getAttachment());
//            obj.put("content",email.getContent());
//            obj.put("subject",email.getSubject());
//            obj.put("sendTime",email.getSendTime());
//            rubbishObjects.add(obj);
//        }
//        return ApiRestResponse.success(rubbishObjects);
//    }
}
